package com.tongzhan.controller;

import com.alibaba.nacos.common.utils.Md5Utils;
import com.tongzhan.base.RegUtil;
import com.tongzhan.base.Return;
import com.tongzhan.entity.User;
import com.tongzhan.entity.religion.Duties;
import com.tongzhan.service.UserService;
import com.tongzhan.utils.SnowFlakeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RequestMapping("/user")
@RestController
public class UserController {

    @Resource
    private UserService userService;

    /**
     * 用户登录接口
     *
     * @param username 用户名
     * @param password 密码
     * @return Return
     */
    @PostMapping("/login")
    public Return login(HttpServletResponse response, String username, String password) {
        if (StringUtils.isEmpty(username) || "".equals(username.trim()) || StringUtils.isEmpty(password) || "".equals(password.trim())) {
            return new Return(Return.MISS_PARAM, "用户名和密码不能为空");
        }
        return userService.login(response, username.trim(), password);
    }

    /**
     * 权限列表
     *
     * @return
     */
    @GetMapping("/userDutyList")
    public Return userDutyList() {
        //1-党派 2-侨台 3-乡贤 4-宗教
        List<Duties> list = userService.userDutyList();
        return Return.getSuccessResult(list);
    }

    /**
     * 添加用户
     *
     * @param userName 用户名
     * @param realName 真实姓名
     * @param duties   职务
     * @param roleId   权限id*********
     * @return
     */
    @PostMapping("/addUser")
    public Return addUser(String userName, String realName, String duties, String roleId, String url,
                          String streetCode, String villageCode) {
        if (StringUtils.isEmpty(userName) || "".equals(userName.trim())
                || StringUtils.isEmpty(realName) || "".equals(realName.trim())
                || StringUtils.isEmpty(duties) || "".equals(duties.trim()) || StringUtils.isEmpty(roleId)) {
            return new Return(Return.MISS_PARAM, "参数缺失");
        }
        if (userName.trim().length() > 10) {
            return Return.getErrorResult("用户名过长");
        }
        if (realName.trim().length() > 10) {
            return Return.getErrorResult("真实姓名过长");
        }
        if (duties.trim().length() > 20) {
            return Return.getErrorResult("职务输入过长");
        }
        Long count = userService.findUserByName(userName, 3);
        if (count > 0) {
            return Return.getErrorResult("用户名已经存在!");
        }
        User user = new User();
        SnowFlakeUtils snowFlake = new SnowFlakeUtils(2, 2);
        user.setUserId(String.valueOf(snowFlake.nextId()));
        user.setUserName(userName.trim());
        user.setRealName(realName.trim());
        user.setDuties(duties.trim());
        user.setDutiesCode(roleId);
        user.setPassWord(Md5Utils.getMD5("123456".getBytes()));
        user.setPicture(url);
        switch (roleId) {
            case "z1":
                //街道
                if (StringUtils.isEmpty(streetCode)) {
                    return new Return(Return.FAIL, "请选择街道信息");
                }
                break;
            case "c1":
                //村社区
                if (StringUtils.isEmpty(streetCode)) {
                    return new Return(Return.FAIL, "请选择街道信息");
                }
                if (StringUtils.isEmpty(villageCode)) {
                    return new Return(Return.FAIL, "请选择村庄信息");
                }
                break;
        }
        user.setStreetCode(streetCode);
        user.setVillageCode(villageCode);
        return userService.addUser(user);
    }

    /**
     * 更改密码
     *
     * @param userId      用户id
     * @param oldPassword 旧密码
     * @param newPassword 新密码
     * @return
     */
    @PostMapping("/updatePsd")
    public Return changePassword(String userId, String oldPassword, String newPassword) {
        if (StringUtils.isEmpty(newPassword) || "".equals(newPassword.trim())
                || StringUtils.isEmpty(oldPassword) || "".equals(oldPassword) || userId == null) {
            return new Return(Return.MISS_PARAM, "参数缺失");
        }
        User user = userService.findUserById(userId);
        if (user != null) {
            if (!oldPassword.equals(user.getPassWord())) {
                return Return.getErrorResult("原密码输入错误!");
            }
            if (newPassword.equals(oldPassword)) {
                return Return.getErrorResult("新密码不能与旧密码相同!");
            }
            long l = userService.changePassword(userId, newPassword);
            if (l > 0) {
                return Return.getSuccessResult("修改成功");
            } else {
                return Return.getErrorResult("修改失败");
            }
        }

        return Return.getErrorResult("修改失败");
    }

    /**
     * 删除用户
     *
     * @param userId
     * @return
     */
    @PostMapping("/delUser")
    public Return delUser(String userId) {
        if (StringUtils.isEmpty(userId)) {
            return Return.getMissParamResult();
        }
        //调用service方法
        long l = userService.delUser(userId);
        if (l > 0) {
            return Return.getSuccessResult("删除成功");
        }
        return Return.getErrorResult("删除失败");
    }

    /**
     * @param page 页码
     * @param size 每页显示条数
     * @param type 用户类型
     * @return
     */
    @PostMapping("/userList")
    public Return userList(Integer page, Integer size, Integer type) {

        page = page == null ? 0 : page - 1;
        //调用service方法
        Map<String, Object> map = userService.getUserList(page, size, type);
        return Return.getSuccessResult(map);
    }

    /**
     * 更新用户
     *
     * @param realName 真实姓名
     * @param duties   职务
     * @param userId   用户id
     * @param phone    手机号
     * @return
     */
    @PostMapping("/updateUser")
    public Return updateUser(String realName, String duties, String userId, String phone) {
        if (userId == null) {
            return Return.getMissParamResult();
        }
        //调用service方法
        if (phone != null) {
            //验证手机号格式是否正确
            boolean b = RegUtil.isMobilePhone(phone);
            if (!b) {
                return Return.getErrorResult("手机号输入格式错误!");
            }
        }
        long l = userService.updateUser(realName, duties, userId, phone);
        if (l >= 0) {
            return Return.getSuccessResult("编辑成功");
        }
        return Return.getErrorResult("编辑失败");
    }

    /**
     * 根据用户id获取用户信息接口
     *
     * @param userId 用户id
     * @return Return
     */
    @RequestMapping("/getUserInfo")
    public Return getUserInfo(String userId) {
        if (StringUtils.isEmpty(userId)) {
            return new Return(Return.FAIL, "参数缺失");
        }
        return Return.getSuccessResult(userService.findUserById(userId));
    }
}
